package cc.catface.api.task;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component//有该注解才能注入bean,才能被@Autowired引入
public class ShowTask {

    /*静态任务,cron.setting中配置时间规则,App中启动*/
    public void staticPing() {
        log.info("staticPing(), at:{}", new Date().toLocaleString());
    }

    /*动态任务,接口控制启动或停止*/
    private final String re = "*/2 * * * * *";
    private String scheduleId;

    public String dynamicPing() {
        String jobId = CronUtil.schedule(re, new Task() {
            @Override
            public void execute() {
                log.info("dynamicPing(), at:{}", new Date().toLocaleString());
            }
        });
        if (!StringUtils.isEmpty(jobId)) {
            scheduleId = jobId;
            return scheduleId;
        }
        return null;
    }

    public void removeDynamicPing() {
        CronUtil.remove(scheduleId);
    }
}
